<?php

namespace app\api\service;

use app\api\config\WxPayService;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use Exception;
use app\api\service\Order;
use app\api\model\Order as OrderModel;
use app\lib\enum\OrderStatusEnum;
use think\Log;

class Pay
{
    private $orderID;
    private $orderNo;

    function __construct($orderID)
    {
        if (!$orderID) {
            throw new Exception("订单号不允许为空");
        }
        $this->orderID = $orderID;
    }

    public function pay()
    {
        //订单号可能不存在
        //订单号存在，但可能与当前用户不匹配
        //订单可能已被支付
        //进行库存量检测
        $this->checkOrderValid();
        $orderService = new Order();
        $status = $orderService->checkOrderStock($this->orderID);
        if (!$status['pass']) {
            return $status;
        }
        return $this->makeWxPreOrder($status['orderPrice']);
    }

    private function makeWxPreOrder($totalPrice)
    {

        $openid = Token::getCurrentTokenVar("openid");
        if (!$openid) {
            return new TokenException();
        }

        $wxservice = new WxPayService();
        $config = $wxservice->getconfig();
        try {
            $resp = $wxservice->builder()
                ->chain('v3/pay/transactions/jsapi')
                ->post([
                    'json' => [
                        'mchid' => $config['merchantId'],
                        'out_trade_no' => $this->orderNo,
                        'appid' => $config['appid'],
                        'description' => '零食商贩',
                        // TODO 回调地址
                        'notify_url' => 'https://www.weixin.qq.com/v1/pay/notify',
                        'amount' => [
                            'total' => $totalPrice * 100,
                            'currency' => 'CNY'
                        ],
                        'payer' => [
                            // 'openid'=> $openid,
                            'openid' => 'oqFAE5ryeUA2KTN6qF1YLwueMdm4'
                        ]
                    ]
                ]);
            return $resp;
        } catch (Exception $e) {
            // 进行错误处理
            Log::record("errorMessage", $e->getMessage(), PHP_EOL);
            if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                $r = $e->getResponse();
                Log::record("获取微信预支付订单失败");
                Log::record("errorCode", $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL);
                Log::record("errorbody", $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL);
            }
            Log::record("errorTraceAsString", $e->getTraceAsString(), PHP_EOL);
        }
    }

    private function checkOrderValid()
    {
        $order = OrderModel::where('id', '=', $this->orderID)->find();
        if (!$order) {
            throw new OrderException();
        }
        if (!Token::isValidOperate($order->user_id)) {
            throw new TokenException([
                'msg' => '订单与用户不匹配',
                'errorCode' => '10003'
            ]);
        }
        if ($order->status != OrderStatusEnum::UNPAID) {
            throw new OrderException([
                'msg' => '订单已支付过了',
                'errorCode' => '80003',
                'code' => '400'
            ]);
        }
        $this->orderNo = $order->order_no;
        return true;
    }
}